package com.lczyfz.istep.common.utils;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.constants.ResourceConstants;
import com.lczyfz.istep.modules.resource.entity.ResourceFile;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jw on 2016/11/18.
 */
public class SysUploadUtils implements Serializable {
    private static final long serialVersionUID = 1L;
    public static final long UNITSIZE = 314572800;
    // 最大文件大小
    private long maxSize = UNITSIZE;
    // 定义允许上传的文件扩展名
    private Map<String, String> extMap = new HashMap<String, String>();
    // 文件的目录名
    private String dirName = "resource";
    //前端标签名称，默认是f
    private String divName = "file";
    //文件上传结果信息
    private String message;
    //是否成功
    private boolean success;
    //文件本地保存路径,单文件
    private String filePath;
    //文件名称,单文件
    private String fileSrcName ;
    //文件本地保存路径,多文件
    private String[] filePaths ;
    //文件名称,多文件
    private String[] fileSrcNames;


    public void setMaxSize(long maxSize) {
        this.maxSize = maxSize;
    }

    public SysUploadUtils() {
        // 其中images,flashs,medias,files,对应文件夹名称,对应dirName
        // key文件夹名称
        // value该文件夹内可以上传文件的后缀名
        extMap.put("images", "gif,jpg,jpeg,png,bmp");
        extMap.put("flashs", "swf,flv");
        extMap.put("medias", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
        extMap.put("files", "doc,docx,pdf,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,gif,jpg,jpeg,png,bmp,apk,ipa");

    }
    public SysUploadUtils(String divName) {
        this.divName = divName;
        // 其中images,flashs,medias,files,对应文件夹名称,对应dirName
        // key文件夹名称
        // value该文件夹内可以上传文件的后缀名
        extMap.put("images", "gif,jpg,jpeg,png,bmp");
        extMap.put("flashs", "swf,flv");
        extMap.put("medias", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("files", "pdf,doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,gif,jpg,jpeg,png,bmp,apk,ipa");

    }
    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this);
    }
    /**
     * 单文件上传
     *
     * @param request
     * @return 操作结果
     */
    public ResourceFile uploadFile(HttpServletRequest request,String type) {
        Map resultMap = new HashMap();
        //转型为MultipartHttpRequest
        MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;
        //获得文件,f为前端标签name。
        MultipartFile file  =  multipartRequest.getFile(this.divName);
        if(file==null||file.isEmpty())
        	return null;
        return saveFile(file,type);
    }
    /**
     * 单文件上传
     *
     * @param file
     * @return 操作结果
     */
    public ResourceFile uploadFile(MultipartFile file,String type) {
        if(file.isEmpty())
            return null;
        return saveFile(file,type);
    }

    /**
     * 多文件上传
     *
     * @param request,
     * @return 操作结果
     */
    public List<ResourceFile> uploadFiles(HttpServletRequest request,String type) {
        Map resultMap = new HashMap();
//        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //转型为MultipartHttpRequest
        if (request.getClass() == ShiroHttpServletRequest.class){
            List<ResourceFile> list = new ArrayList<>();
            return list;
        }
        MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;
        System.out.println("-------------"+multipartRequest.getMultiFileMap());
        //获得文件,f为前端标签name。
        List<MultipartFile> fileList = new ArrayList<MultipartFile>();
        List<ResourceFile> lgSysFileList = new ArrayList<ResourceFile>();
        fileList = multipartRequest.getFiles(this.divName);
        this.filePaths = new String[fileList.size()];
        this.fileSrcNames = new String[fileList.size()];
        for (int i=0 ; i < fileList.size() ; i++){
            ResourceFile sysFile = new ResourceFile();
            sysFile = saveFile(fileList.get(i),type);
            System.out.print("上传工具类里面的sysFile"+sysFile);

            if (sysFile == null){
                this.message = "上传第" + i + "个文件出错," + this.message;
                return lgSysFileList;
            }else {
                lgSysFileList.add(sysFile);
                this.success = true;
                this.filePaths[i] = this.filePath;
                this.fileSrcNames[i] = this.fileSrcName;
                this.filePath = "";
                this.fileSrcName = "";
            }
        }
        this.message = "上传"+fileList.size()+"个文件成功";
        return lgSysFileList;
    }
    /** **********************私有方法********************************* */
    /**
     * 文件验证
     *
     * @param file
     * @return 验证结果
     */
    private boolean validateFile(MultipartFile file,String type) {
        if(file == null || file.getSize() == 0 ){
            this.message = "上传文件不存在";
            return false;
        }

        if (this.maxSize == -1 ){
            //-1表示不限制大小
        }else if (file.getSize() > this.maxSize || file.getSize() < 0){
            this.message = "上传文件过大";
            return false;
        }
        //文件名称中包含多个"."
        String fileName = file.getOriginalFilename();
        if (fileName.split(".").length > 2){
            this.message = "文件格式不正确";
            return false;
        }
//        extMap.put("images", "gif,jpg,jpeg,png,bmp");
//        extMap.put("flashs", "swf,flv");
//        extMap.put("medias", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
//        extMap.put("files", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,gif,jpg,jpeg,png,bmp,apk,ipa");
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
        System.out.println("----suffix----"+suffix);

//        if(!this.extMap.get("medias").toString().contains(suffix)){
//            this.message = "文件格式不正确";
//            return false;
//        }
        if(type.equals(ResourceConstants.videoMateria))
        {
            if(!this.extMap.get("medias").toString().contains(suffix)){
                this.message = "文件格式不正确";
                return false;
            }
        }else if(type.equals(ResourceConstants.imageFile))
        {

        }else
        {
            if(!this.extMap.get("files").toString().contains(suffix)){
                this.message = "文件格式不正确";
                return false;
            }
        }
        return true;
    }
    /**
     * 单文件上传
     *
     * @param file
     * @return 是否操作成功
     */
    public ResourceFile saveFile(MultipartFile file,String type) {
        System.out.print("调用了一次");

        ResourceFile lgSysFile = new ResourceFile();
        //文件验证
        if (!validateFile(file,type)){
            this.success = false;
            return lgSysFile;
        }
        System.out.println("文件验证通过===");

        //得到上传的文件名称
        String fileName = file.getOriginalFilename();
        //得到后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        //为了保存名称的唯一性，使用uuid
        String name = IdGen.uuid();
        //客户端访问路径
        String filePath = Global.USERFILES_BASE_URL+this.dirName + "/" + name + "."+suffix;
        System.out.println("----filePath----"+filePath);
        System.out.println("----fileName----"+fileName);

        //本地保存路径
//        String fileLocalPath = Global.getUserfilesBaseDir().replace("/","")+ "userfiles\\" + this.dirName + "\\" + name + "."+suffix;
        //本地保存路径
        String fileLocalPath = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + this.dirName + "/" + name + "."+suffix;

        System.out.println("----fileLocalPath----" + fileLocalPath);
        //创建目录
        File saveDirFile = new File(fileLocalPath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        try {
//            LgSysFileService lgSysFileService = ApplicationContext.get(LgSysFileService.class);


            file.transferTo(saveDirFile);
            lgSysFile.setUrl(filePath);
            lgSysFile.setName(fileName);
            lgSysFile.setFormat(suffix);
            lgSysFile.setLocalUrl(fileLocalPath);
            this.message = "上传成功!";
            this.success = true;
            this.filePath = filePath;
            this.fileSrcName = fileName;
            return lgSysFile;
        } catch (Exception e) {
            e.printStackTrace();
            this.message = e.getMessage();
            this.success = false;
            return lgSysFile;
        }
    }
    /** **********************get/set方法********************************* */
    public Map<String, String> getExtMap() {
        return extMap;
    }

    public void setExtMap(Map<String, String> extMap) {
        this.extMap = extMap;
    }

    public String getDirName() {
        return dirName;
    }

    public void setDirName(String dirName) {
        this.dirName = dirName;
    }
    public long getMaxSize() {
        return maxSize;
    }

    public String getMessage() {
        return message;
    }

    public String getFilePath() {
        return filePath;
    }

    public String getDivName() {
        return divName;
    }

    public void setDivName(String divName) {
        this.divName = divName;
    }

    public String[] getFilePaths() {
        return filePaths;
    }

    public String getFileSrcName() {
        return fileSrcName;
    }

    public String[] getFileSrcNames() {
        return fileSrcNames;
    }

    public boolean isSuccess() {
        return success;
    }
}
